<template>
  <RangePicker
    :value="hackValue || value"
    :disabled-date="disabledDate"
    :allowClear="false"
    @change="onChange"
    @openChange="onOpenChange"
    @calendarChange="onCalendarChange"
    :valueFormat="valueFormat"
  />
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { RangePicker } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';

const props = defineProps({
  formState: {
    type: Object,
    requried: true,
  },
  defaultValue: {
    type: Array,
    default: () => [],
  },
  maxDay: {
    type: Number,
    default: 31,
  },
  valueFormat: {
    type: String,
    default: 'YYYY-MM-DD',
  },
  type: {
    type: String,
    default: 'day',
  },
});
const emit = defineEmits(['change']);

watch(
  () => props.formState,
  (val: any) => {
    value.value = val.time;
  },
  { deep: true },
);
const { type } = props;
type RangeValue = [Dayjs, Dayjs];
const dates = ref<RangeValue>();
const value = ref<any>();
const hackValue = ref<RangeValue>();
value.value = props.defaultValue;
const disabledDate = (current: Dayjs) => {
  // 今天
  const yesterday = dayjs().startOf('day');
  // 当前周第一天
  const oneDayTime = 24 * 60 * 60 * 1000;
  const time: any = dayjs().endOf('week');
  const MondayTime = dayjs(time - 6 * oneDayTime).format('YYYY-MM-DD');
  // 当月第一天
  const monthDay = dayjs().startOf('month').format('YYYY-MM-DD');
  if (type === 'day' && current && current.endOf('day').isAfter(yesterday)) {
    return true;
  }

  if (type === 'week' && current && current.endOf('day').isAfter(MondayTime)) {
    return true;
  }

  if (type === 'month' && current && current.endOf('day').isAfter(monthDay)) {
    return true;
  }

  if (!dates.value || (dates.value as any).length === 0) {
    return false;
  }
  const tooLate =
    dates.value[0] && current.diff(dates.value[0], 'days') > props.maxDay;
  const tooEarly =
    dates.value[1] &&
    dayjs(dates.value[1]).diff(current, 'days') > props.maxDay;

  return tooEarly || tooLate;
};

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any;
    hackValue.value = [] as any;
  } else {
    hackValue.value = undefined;
  }
};

const onChange = (val: RangeValue) => {
  value.value = val;
  emit('change', val);
};

const onCalendarChange = (val: RangeValue) => {
  dates.value = val;
};
</script>
